<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use app\common\controller\Util;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Hook;
use think\Validate;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login','teacherRegister','phoneLogin'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'teacher'   => [1,'red','badge'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }
    /**
     * 教师注册
     */
    public function teacherRegister(){
        $param = $this->validates();
        $phone = $param['phone'];
        $password = $param['password'];
        $code = $param['invite_code'];
        // 数据校验END
//        插入user表
//        思路：默认注册的教师不能登录，需要管理员审核之后才可以登录
//        $ret = $this->auth->register($phone, $password, '', $phone, ['group_id' => 2]);
//        if ($ret) {
//            res作为admin的id标识
//            插入admin表registerTeacher
            $res = Db::name('admin')->where('username',$phone)->find();
            if(!empty($res)){
                $this->error('该账号已注册');
            }
            $ret = $this->registerTeacher($phone, $password, '', $phone, []);
            Db::name("auth_group_access")->insert(['uid' => $ret, 'group_id' => 7]);
//        }
        $icode = Util::getInviteCode();
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $params['invite_code'] = $icode;
//            $params['user_id'] = $data['userinfo']['user_id'];
            $params['admin_id'] = $ret;
            $params['phone'] = $phone;
            $params['name'] = $phone;
            $params['nick_name'] = $phone;
            $params['register_time'] = date("Y-m-d H:i:s");
            $params['create_time'] = date("Y-m-d H:i:s");
//            插入teacher表
            $result = Db::name('teacher')->insert($params);
            $tid = Db::name('teacher')->getLastInsID();
            $hooks_data = [
                // 用户姓名
                'name' => '教师',
                // 用户所在表id
                'uid' => $tid,
                // 用户类型 student / teacher / help
                'type' => 'teacher',
            ];
            $data = Hook::listen("createAccountForUser", $hooks_data, '', true);

            if (!empty($code)) {
                $teacher_invest = [
                    'role' => 'teacher',
                    'uid' => $tid,
                    'invite_code' => $code,
                ];
                Hook::listen("createTeacherInvest", $teacher_invest, '', true);
            }
            $url = 'index/index';
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($phone, $password,86400);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $params['name'], 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * Notes:手机号登录
     * User: XingLiangRen
     * Date: 2020/9/9
     * Time: 11:47
     */
    public function phoneLogin(){
        $param = $this->request->post();
        // 数据校验START
        $data = $this->validate($param, [
            'phone' => 'require|regex:/^1[3456789]\d{9}$/',
            'code' => 'require|regex:/^\d{6}$/i',
        ], [
                'phone.require' => '手机号码必填',
                'phone.regex' => '手机号码格式错误',
                'code.require' => '短信验证码为必填',
                'code.regex' => '短信验证码格式错误',
            ]
        );
        if (!empty($data) && $data !== true) {
             $this->error($data);
        }
        // 验证验证码的正确
        $smsResult = Sms::check($param['phone'], $param['code'], 'register');
        $smsResult ?: $this->error("验证码错误");
        $url = 'index/index';
        AdminLog::setTitle(__('Login'));
        $result = $this->auth->codeLogin($param['phone'],86400);
        if ($result === true) {
            Hook::listen("admin_login_after", $this->request);
            $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $param['phone'], 'avatar' => $this->auth->avatar]);
        } else {
            $msg = $this->auth->getError();
            $msg = $msg ? $msg : __('Username or password is incorrect');
            $this->error($msg, $url, ['token' => $this->request->token()]);
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        Hook::listen("admin_logout_after", $this->request);
        $this->success(__('Logout successful'), 'index/login');
    }
    private function validates(){
        $param = $this->request->post();
        // 数据校验START
        $data = $this->validate($param, [
            'phone' => 'require|regex:/^1[3456789]\d{9}$/',
            'password' => 'require|regex:/^[0-9a-z_.]{8,16}$/i',
        ], [
                'phone.require' => '手机号码必填',
                'phone.regex' => '手机号码格式错误',
                'password.require' => '密码为必填',
                'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
            ]
        );
        if (!empty($data) && $data !== true) {
            return $this->error($data);
        }
        // 验证验证码的正确
        $smsResult = Sms::check($param['phone'], $param['code'], 'register');
        $smsResult ?: $this->error("验证码错误");
        return  $param;
    }

    /**
     * 注册用户
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param array $extend 扩展参数
     * @return boolean
     */
    private function registerTeacher($username, $password, $email = '', $mobile = '', $extend = [])
    {

        //账号注册时需要开启事务,避免出现垃圾数据
        try {
            $params['username'] = $username;
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($password) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            $params['status'] = 'normal';
            Db::name("admin")->insert($params);
            return Db::getLastInsID();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
    }
}
